/**
 * @module
 * @author      nayo
 * @date        2020/9/23 4:17 下午
 * @version     1.0
 */
import UserApi from '@/common/api/UserApi';
import utils from '@/common/utils';
import jwt_decode from 'jwt-decode';

export default {
	state: {
		expiresAt: undefined,
		token: undefined,
		loginStatus: false,
		user: {}
	},
	mutations: {
		SET_TOKEN(state, data) {
			state.token = data.token;
			state.expiresAt = data.expiresAt * 1000;
		},
		STE_USER(state, user) {
			state.user = user;
		},
		SET_LOGIN_STATUS(state, loginStatus) {
			state.loginStatus = loginStatus;
		}
	},
	actions: {
		async login({commit}, data) {
			return await UserApi.auth(data).then(async res => {
				return await utils.responseHandler(res).then(async ({data}) => {
					commit('SET_TOKEN', data)
					let decoded = jwt_decode(data.token);
					commit('STE_USER', decoded.User);
					commit('SET_LOGIN_STATUS', true);
					return true
				});
			})
		},
		async logout({commit}) {
		}
	},
	getters: {
		token: (s) => s.token,
		loginStatus: s => s.loginStatus,
		user: s => s.user,
		expiresAt: s => s.expiresAt
	}
}
